<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="50%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row :span="20">
        <el-col :span="16">
          <el-form-item label="主题" prop="theme">
            <el-input v-model="formData.theme" placeholder="请输入主题" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发起部门" prop="deptId">
            <el-tree-select
              v-model="formData.deptId"
              :data="deptList"
              :props="defaultProps"
              check-strictly
              node-key="id"
              placeholder="请选择发起部门"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="内容简介" prop="theme">
        <el-input v-model="formData.content" placeholder="请输入内容简介" />
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="有效日期" prop="daterange">
            <el-date-picker
              v-model="formData.daterange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 公函人员 -->
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="查阅公函人员" name="first">
          <el-button type="primary" plain @click="openUserForm()">
            选择公函人员
          </el-button>
          <el-table ref="multipleTableRef" :data="tableUserData" style="width: 100%; margin-top: 10px; height: 200px;">
            <el-table-column label="序号" type="index"  header-align="center" align="center" width="60px" fixed />
            <el-table-column label="用户昵称" align="center" prop="nickname" :show-overflow-tooltip="true" />
            <el-table-column label="部门" align="center" key="deptName" prop="deptName" :show-overflow-tooltip="true">
              <template #default="scope">
                {{ deptList2.find((dept) => dept.id === scope.row.deptId)?.name }}
              </template>
            </el-table-column>
            <el-table-column label="手机号码" align="center" prop="mobile" width="120" />
            <el-table-column label="操作" align="center" fixed="right" width="140px">
              <template #default="scope">
                <el-button
                  size="small"
                  link
                  type="danger"
                  @click.prevent="deleteUserRow(scope.$index, tableUserData)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="附件列表" name="second">
          <el-upload
            name="file"
            ref="uploadRef"
            class="upload-file-uploader"
            v-model:file-list="fileList"
            :show-file-list="false"
            :action="uploadUrl"
            :http-request="httpRequest"
            :auto-upload="autoUpload"
            :before-upload="beforeUpload"
            :drag="drag"
            :limit="props.limit"
            :multiple="props.limit > 1"
            :on-error="excelUploadError"
            :on-exceed="handleExceed"
            :on-remove="handleRemove"
            :on-success="handleFileSuccess"
          >
            <el-button type="primary">
              <Icon icon="ep:upload-filled" />
              选取文件
            </el-button>
            <template v-if="isShowTip" #tip>
              <div style="font-size: 10px">
                1.格式为 <b style="color: #f56c6c">{{ fileType.join('/') }}</b> 的文件; 2.大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
              </div>
            </template>
          </el-upload>
          
          <el-table ref="multipleTableRef" :data="uploadList" style="width: 100%; margin-top: 10px; height: 200px;">
            <el-table-column label="序号" type="index"  header-align="center" align="center" width="60px" fixed />
            <el-table-column label="文件名称" align="center" prop="name" :show-overflow-tooltip="true" />
            <el-table-column label="文件路径" align="center" prop="url" :show-overflow-tooltip="true" />
            <el-table-column label="操作" align="center" fixed="right" width="140px">
              <template #default="scope">
                <el-link type="primary" download :href="scope.row.url" :underline="false" target="_blank">下载</el-link>
                <el-button
                  size="small"
                  link
                  type="danger"
                  @click.prevent="deleteFileRow(scope.$index, uploadList)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <el-form-item label="公函内容">
        <Editor v-model="formData.remark" height="200px" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm('2')" type="primary" :disabled="formLoading">提 交</el-button>
      <el-button @click="submitForm('1')" type="primary" :disabled="formLoading">保 存</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <!-- 表单弹窗：选择学员 -->
  <SelectUser style="width: 50%" ref="formUserRef" @send-data="updateUserData" />
</template>

<script setup lang="ts">
import { BaseOfficialLetterApi, BaseOfficialLetterVO } from '@/api/infra/baseofficialletter'
import * as UserApi from '@/api/system/user'
import * as DeptApi from '@/api/system/dept'

import SelectUser from './SelectUser.vue'
import { CommonStatusEnum } from '@/utils/constants'
import type { UploadInstance, UploadProps, UploadRawFile, UploadUserFile } from 'element-plus'
import { useNewUpload } from '@/components/UploadFile/src/useUpload'
import { UploadFile } from 'element-plus/es/components/upload/src/upload'
import { propTypes } from '@/utils/propTypes'
import { defaultProps, handleTree } from '@/utils/tree'

const { uploadUrl, httpRequest } = useNewUpload()

// ========== 上传相关 ==========
const uploadRef = ref<UploadInstance>()
const uploadList = ref<UploadUserFile[]>([])
const fileList = ref<UploadUserFile[]>([])
const uploadNumber = ref<number>(0)

const props = defineProps({
  modelValue: propTypes.oneOfType<any>([]).isRequired,
  title: propTypes.string.def('文件上传'),
  fileType: propTypes.array.def(['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'pdf', 'png', 'jpg', 'jpeg']), // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileSize: propTypes.number.def(20), // 大小限制(MB)
  limit: propTypes.number.def(5), // 数量限制
  autoUpload: propTypes.bool.def(true), // 自动上传
  drag: propTypes.bool.def(false), // 拖拽上传
  isShowTip: propTypes.bool.def(true) // 是否显示提示
})

/** 公函 表单 */
defineOptions({ name: 'BaseOfficialLetterForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const officialLetterId = ref() // 弹窗的是否展示
const fileData = ref<any>([]) // 文件数据
const deptList = ref<Tree[]>([]) // 树形结构
const deptList2 = ref<any[]>([]) // 部门列表
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formRef = ref() // 表单 Ref
const formData = ref({
  id: undefined,
  theme: undefined,
  daterange: undefined,
  startDate: undefined,
  endDate: undefined,
  fileExists: undefined,
  content: undefined,
  remark: undefined,
  imageAddress: undefined,
  status: CommonStatusEnum.ENABLE,
  fileData: undefined,
  detailData: undefined,
  deptId: undefined
})

const formRules = reactive({
  theme: [{ required: true, message: '主题不能为空', trigger: 'blur' }],
  content: [{ required: true, message: '内容简介不能为空', trigger: 'blur' }],
  daterange: [{ required: true, message: '有效日期不能为空', trigger: 'blur' }]
})

/** 打开弹窗 */
const activeName = ref('')
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  uploadList.value = []
  tableUserData.value = []
  activeName.value = 'first'
  // 修改时，设置数据
  if (id) {
    officialLetterId.value = id
    formLoading.value = true
    try {
      formData.value = await BaseOfficialLetterApi.getBaseOfficialLetter(id)
      formData.value.daterange = [formData.value.startDate, formData.value.endDate]

      tableUserData.value = await BaseOfficialLetterApi.getLetterUserList(id)
      uploadList.value = await BaseOfficialLetterApi.getLetterFileList(id)
    } finally {
      formLoading.value = false
    }
  }
  // 加载部门树
  deptList.value = handleTree(await DeptApi.getAllList())
  // 加载部门树
  deptList2.value = await DeptApi.getAllList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 添加/修改操作 */
const formUserRef = ref()
const openUserForm = () => {
  formUserRef.value.open(officialLetterId.value)
}

const receivedUserData = ref('')
const tableUserData = ref<UserApi.UserVO[]>([])
const updateUserData = async (data) => {
  receivedUserData.value = data
  if (data) {
    for (let i = 0; i < data.value.length; i++) {
      const index = tableUserData.value.filter((item) => item.id === data.value[i].id)
      if (index.length > 0) {
        message.warning('【'+data.value[i].nickname + '】该人员已添加')
      } else {
        tableUserData.value.push(data.value[i])
      }
    }
  }
}

// 文件上传之前判断
const beforeUpload: UploadProps['beforeUpload'] = (file: UploadRawFile) => {
  if (fileList.value.length >= props.limit) {
    message.error(`上传文件数量不能超过${props.limit}个!`)
    return false
  }
  let fileExtension = ''
  if (file.name.lastIndexOf('.') > -1) {
    fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
  }
  const isImg = props.fileType.some((type: string) => {
    if (file.type.indexOf(type) > -1) return true
    return !!(fileExtension && fileExtension.indexOf(type) > -1)
  })
  const isLimit = file.size < props.fileSize * 1024 * 1024
  if (!isImg) {
    message.error(`文件格式不正确, 请上传${props.fileType.join('/')}格式!`)
    return false
  }
  if (!isLimit) {
    message.error(`上传文件大小不能超过${props.fileSize}MB!`)
    return false
  }
  const existFile = fileList.value.slice(0, fileList.value.length - 1).find(f => f.name === file.name)
  if (existFile) {
    message.error(`当前文件已经存在!`)
    return false
  }
  message.success('正在上传文件，请稍候...')
  uploadNumber.value++
}
// 文件上传成功
const handleFileSuccess: UploadProps['onSuccess'] = (res: any): void => {
  uploadList.value.push({ uid: res.data.id, name: res.data.name, url: res.data.url })
  message.success('上传成功')
}
// 文件数超出提示
const handleExceed: UploadProps['onExceed'] = (): void => {
  message.error(`上传文件数量不能超过${props.limit}个!`)
}
// 上传错误提示
const excelUploadError: UploadProps['onError'] = (): void => {
  message.error('导入数据失败，请您重新上传！')
}
// 删除上传文件
const handleRemove = (file: UploadFile) => {
  const index = fileList.value.map((f) => f.name).indexOf(file.name)
  if (index > -1) {
    fileList.value.splice(index, 1)
  }
}

const deleteFileRow = (index, rows) => {
  rows.splice(index, 1)
}

/** 提交表单 */
const userList = ref<any>([]) // 线索id
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async (flag) => {
  // formData.fileExists
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  fileData.value = []
  for (let i = 0; i < uploadList.value.length; i++) {
    const UserCourse = {
      fileId: uploadList.value[i].uid
    }
    fileData.value.push(UserCourse)
  }
  userList.value = []
  for (let i = 0; i < tableUserData.value.length; i++) {
    const UserCourse = {
      userId: tableUserData.value[i].id,
      userName: tableUserData.value[i].nickname,
      status: CommonStatusEnum.ENABLE,
      totalViewNum: CommonStatusEnum.ENABLE
    }
    userList.value.push(UserCourse)
  }
  try {
    const data = formData.value as unknown as BaseOfficialLetterVO
    data.startDate = formData.value.daterange[0]
    data.endDate = formData.value.daterange[1]
    data.fileData = fileData.value
    data.detailData = userList.value
    if (uploadList && uploadList.value.length > 0) {
      data.fileExists = 97
    } else {
      data.fileExists = 98
    }
    if (flag === '1') {
      data.status = CommonStatusEnum.ENABLE
    } else {
      data.status = CommonStatusEnum.DISABLE
    }
    if (formType.value === 'create') {
      await BaseOfficialLetterApi.createBaseOfficialLetter(data)      
      if (flag === 1) {
        message.success(t('common.createSuccess'))
      } else {
        message.success(t('common.submitSuccess'))
      }
    } else {
      await BaseOfficialLetterApi.updateBaseOfficialLetter(data)
      if (flag === 1) {
        message.success(t('common.updateSuccess'))
      } else {
        message.success(t('common.submitSuccess'))
      }
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    theme: undefined,
    daterange: undefined,
    startDate: undefined,
    endDate: undefined,
    fileExists: undefined,
    content: undefined,
    remark: undefined,
    imageAddress: undefined,
    status: CommonStatusEnum.ENABLE,
    fileData: undefined,
    detailData: undefined,
    deptId: undefined
  }
  formRef.value?.resetFields()
}
</script>